package com.demo.youxuanmall.controller;

import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.service.SystemSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基础控制器，用于处理所有控制器共有的功能
 * 如：加载系统设置到所有页面
 */
@Slf4j
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class BaseController {

    protected final SystemSettingService systemSettingService;
    
    // 使用ConcurrentHashMap作为简单的内存缓存
    private static final Map<String, String> settingsCache = new ConcurrentHashMap<>();
    private static long lastCacheUpdate = 0;
    private static final long CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

    // 默认设置
    private static final Map<String, String> DEFAULT_SETTINGS = new HashMap<>();
    static {
        DEFAULT_SETTINGS.put("siteName", "优选商城");
        DEFAULT_SETTINGS.put("siteLogo", "/static/images/logo.png");
        DEFAULT_SETTINGS.put("siteDescription", "优质商品，优选生活");
        DEFAULT_SETTINGS.put("contactEmail", "support@example.com");
        DEFAULT_SETTINGS.put("contactPhone", "400-123-4567");
    }

    /**
     * 在每个请求处理前执行，将系统设置加载到模型中
     * 使用@ModelAttribute注解，确保每个请求都能获取到系统设置
     */
    @ModelAttribute("siteSettings")
    public Map<String, String> loadSystemSettings(HttpServletRequest request) {
        try {
            // 检查缓存是否有效
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastCacheUpdate > CACHE_DURATION) {
                settingsCache.clear();
                lastCacheUpdate = currentTime;
            }
            
            // 如果缓存为空，则加载设置
            if (settingsCache.isEmpty()) {
                try {
                    // 获取基本设置
                    Result<Map<String, Object>> basicResult = systemSettingService.getSettingsByGroup("basic");
                    if (basicResult != null && basicResult.getCode() == 0 && basicResult.getData() != null) {
                        Map<String, Object> basicSettings = basicResult.getData();
                        
                        // 网站名称
                        if (basicSettings.containsKey("site_name")) {
                            Map<String, Object> siteNameSetting = (Map<String, Object>) basicSettings.get("site_name");
                            if (siteNameSetting != null && siteNameSetting.get("value") != null) {
                                settingsCache.put("siteName", String.valueOf(siteNameSetting.get("value")));
                            }
                        }
                        
                        // 网站Logo
                        if (basicSettings.containsKey("site_logo")) {
                            Map<String, Object> siteLogoSetting = (Map<String, Object>) basicSettings.get("site_logo");
                            if (siteLogoSetting != null && siteLogoSetting.get("value") != null) {
                                settingsCache.put("siteLogo", String.valueOf(siteLogoSetting.get("value")));
                            }
                        }
                        
                        // 网站描述
                        if (basicSettings.containsKey("site_description")) {
                            Map<String, Object> siteDescSetting = (Map<String, Object>) basicSettings.get("site_description");
                            if (siteDescSetting != null && siteDescSetting.get("value") != null) {
                                settingsCache.put("siteDescription", String.valueOf(siteDescSetting.get("value")));
                            }
                        }
                        
                        // 联系邮箱
                        if (basicSettings.containsKey("contact_email")) {
                            Map<String, Object> contactEmailSetting = (Map<String, Object>) basicSettings.get("contact_email");
                            if (contactEmailSetting != null && contactEmailSetting.get("value") != null) {
                                settingsCache.put("contactEmail", String.valueOf(contactEmailSetting.get("value")));
                            }
                        }
                        
                        // 联系电话
                        if (basicSettings.containsKey("contact_phone")) {
                            Map<String, Object> contactPhoneSetting = (Map<String, Object>) basicSettings.get("contact_phone");
                            if (contactPhoneSetting != null && contactPhoneSetting.get("value") != null) {
                                settingsCache.put("contactPhone", String.valueOf(contactPhoneSetting.get("value")));
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("加载系统设置失败", e);
                }
            }
            
            // 创建新的Map返回，避免修改缓存
            Map<String, String> settings = new HashMap<>(DEFAULT_SETTINGS);
            settings.putAll(settingsCache);
            
            return settings;
        } catch (Exception e) {
            log.error("处理系统设置时发生错误", e);
            return new HashMap<>(DEFAULT_SETTINGS);
        }
    }
} 